package com.nuoniu.sibanyun.controller.work;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nuoniu.sibanyun.common.BaseController;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.common.result.HttpResult;
import com.nuoniu.sibanyun.entity.work.WorkPlanContent;
import com.nuoniu.sibanyun.entity.work.WorkPlanSummary;
import com.nuoniu.sibanyun.entity.work.WorkReportUser;
import com.nuoniu.sibanyun.entity.work.WorkSummary;
import com.nuoniu.sibanyun.service.work.IWorkPlanContentService;
import com.nuoniu.sibanyun.service.work.IWorkPlanSummaryService;
import com.nuoniu.sibanyun.service.work.IWorkReportUserService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 工作计划/总结 前端控制器
 * </p>
 *
 * @author baiqiang
 * @since 2020-08-19
 */
@RestController
@RequestMapping("/work/planSummary")
@Api(tags = "工作计划/总结", value = "工作计划/总结")
public class WorkPlanSummaryController extends BaseController {

    @Autowired
    private IWorkPlanSummaryService planSummaryService;
    @Autowired
    private IWorkReportUserService reportUserService;

    /**
     * 获取工作计划/总结列表
     * @author 小啊刚
     * @date 2020-08-14
     */
    @ApiOperation("获取工作计划/总结列表")
    @GetMapping("pageList")
    public HttpResult pageList(Page page, WorkPlanSummary planSummary) {
        return HttpResult.ok(planSummaryService.pageList(page, planSummary));
    }

    /**
     * 保存工作计划/总结
     * @author 小啊刚
     * @date 2020-08-15
     */
    @ApiOperation("保存工作计划/总结")
    @PostMapping("save")
    public HttpResult save(@RequestBody WorkPlanSummary planSummary) throws ParseException {
        UserInfo userInfo = UserThreadLocal.get();

        if(StringUtils.isNotBlank(planSummary.getMyEvaluationContent())) {
            planSummary.setMyEvaluationDate(LocalDateTime.now());
        }

        if (planSummary.getId() != null) {
            WorkPlanSummary form = planSummaryService.getById(planSummary.getId());
            if (form.getStatus() == 1 || form.getReadStatus() == 1) {
                throw new NuoNiuException("已报送,无法修改");
            }

            WorkReportUser reportUser = reportUserService.getDetail(userInfo.getOfficeId(), planSummary.getType(), 3);
            if (planSummary.getId() != null) {
                WorkPlanSummary summary = planSummaryService.getById(planSummary.getId());
                if (summary.getStatus() != 0) {
                    throw new NuoNiuException("已提交,无法修改");
                }

                if (summary.getStatus() == 0 && planSummary.getStatus() == 1) {
                    if (reportUser != null && StringUtils.isNotBlank(reportUser.getDeadline())) {
                        planSummary.setCreateDate(summary.getCreateDate());
                        Boolean flag = checkReport(planSummary, reportUser);
                        if (!flag) {
                            throw new NuoNiuException("提交失败,已超时");
                        }
                    }
                    planSummary.setSubmitDate(LocalDateTime.now());
                }
                planSummaryService.updateById(planSummary);
            }
        } else {
            planSummary.setOfficeId(userInfo.getOfficeId());
            planSummary.setCompanyId(userInfo.getCompanyId());
            planSummary.setCreateUserId(userInfo.getUserId());
            planSummary.setCreateUserName(userInfo.getRealName());
            planSummaryService.save(planSummary);
        }
        return HttpResult.ok();
    }

    /**
     * 删除工作计划/总结
     * @author 小啊刚
     * @date 2020-08-15
     */
    @ApiOperation("删除工作计划/总结")
    @PostMapping("delete")
    public HttpResult delete(@RequestBody List<String> ids) {
        for(String id : ids) {
            WorkPlanSummary workPlanSummary = planSummaryService.getById(id);
            if(workPlanSummary.getStatus() != 0) {
                throw new NuoNiuException("已报送，不能删除");
            }
            planSummaryService.removeById(id);
        }
        return HttpResult.ok();
    }

    /**
     * 报送计划/总结
     * @author 小啊刚
     * @date 2020-08-17
     */
    @ApiOperation("报送计划/总结")
    @PostMapping("submit")
    public HttpResult submit(@RequestBody WorkPlanSummary workSummary) throws ParseException {
        if(workSummary.getSubmitId() == null) {
            throw new NuoNiuException("报送人不能为空");
        }

        UserInfo userInfo = UserThreadLocal.get();
        if(StringUtils.isNotBlank(workSummary.getCcId())) {
            String[] ids = workSummary.getCcId().split(",");
            for(String id : ids) {
                if(workSummary.getSubmitId().equals(id)) {
                    throw new NuoNiuException("报送人和抄送不能相同");
                }
            }
        }

        if(workSummary.getStatus() != 0) {
            throw new NuoNiuException("请选择未报送的总结");
        }

        if(workSummary.getFinishStatus()) {
            throw new NuoNiuException("已存档");
        }

        if(workSummary.getSubmitId().equals(userInfo.getUserId())) {
            throw new NuoNiuException("不能报送给自己");
        }

        WorkReportUser reportUser = reportUserService.getDetail(userInfo.getOfficeId(), workSummary.getType(), 3);
        WorkPlanSummary form = planSummaryService.getById(workSummary.getId());
        workSummary.setCreateDate(form.getCreateDate());
        if(reportUser != null && StringUtils.isNotBlank(reportUser.getDeadline())) {
            Boolean flag = checkReport(workSummary, reportUser);
            if(!flag) {
                throw new NuoNiuException("提交失败,已超时");
            }
        }

        workSummary.setStatus(1);
        workSummary.setReadStatus(0);
        workSummary.setSubmitDate(LocalDateTime.now());
        planSummaryService.updateById(workSummary);
        return HttpResult.ok();
    }

    /**
     * 审核计划/总结
     * @author 小啊刚
     * @date 2020-08-19
     */
    @ApiOperation("审核计划/总结")
    @PostMapping("approval")
    public HttpResult approval(@RequestBody List<WorkPlanSummary> planSummarys) {
        for(WorkPlanSummary planSummary : planSummarys) {
            WorkPlanSummary workPlanSummary = planSummaryService.getById(planSummary.getId());
            if(workPlanSummary.getFinishStatus()) {
                throw new NuoNiuException("已存档, 无需再审核");
            }

            planSummary.setSubmitDate(LocalDateTime.now());
            if(planSummary.getReadStatus().equals(2)) {
                planSummary.setStatus(0);
            } else {
                planSummary.setStatus(1);
            }
        }

        planSummaryService.updateBatchById(planSummarys);
        return HttpResult.ok();
    }

    /**
     * 撤回
     * @author 小啊刚
     * @date 2020-08-26
     */
    @ApiOperation("撤回")
    @PostMapping("returnPlan")
    public HttpResult returnPlan(@RequestBody WorkPlanSummary workPlanSummary) {
        planSummaryService.returnPlan(workPlanSummary);
        return HttpResult.ok();
    }

    @ApiOperation("存档")
    @PostMapping("finish")
    public HttpResult finish(@RequestBody List<String> ids) {
        if(ids.size() == 0) {
            throw new NuoNiuException("请选择数据");
        }

        planSummaryService.finish(ids);
        return HttpResult.ok();
    }

    /**
     * 保存评价
     * @author 小啊刚
     * @date 2020-09-05
     */
    @ApiOperation("保存评价")
    @PostMapping("saveEvaluation")
    public HttpResult saveEvaluation(@RequestBody WorkPlanSummary workPlanSummary) {
        //planSummaryService.updateById(workPlanSummary);
        UserInfo userInfo = UserThreadLocal.get();
        WorkPlanSummary form = planSummaryService.getById(workPlanSummary.getId());

        if(!userInfo.getUserId().equals(form.getSubmitId())) {
            throw new NuoNiuException("被报送人才能评价");
        }

        if(form.getFinishStatus()) {
            throw new NuoNiuException("已存档，不能评价");
        }
//        if(StringUtils.isNotBlank(form.getEvaluationLevel()) && StringUtils.isNotBlank(form.getEvaluationContent())) {
//            throw new NuoNiuException("已评价,不能再次评价");
//        }
        workPlanSummary.setEvaluationDate(LocalDateTime.now());
        workPlanSummary.setReadStatus(1);
        planSummaryService.updateById(workPlanSummary);
        return HttpResult.ok();
    }

    public Boolean checkReport(WorkPlanSummary workSummary, WorkReportUser reportUser) throws ParseException {
        String[] time = reportUser.getDeadline().split(",");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        Calendar calendar = Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        Integer month = calendar.get(Calendar.MONTH) + 1;
        Integer day = calendar.get(Calendar.DATE);
        if(time.length < 3) {
            return true;
        }

        if(workSummary.getType() == 1) { //日
            if(time[0].equals("1")) { //当日
                Date d  = sdf.parse(year + "-" + month + "-" + day + " " + time[1] + ":" + time[2]);
                if(d.getTime() < workSummary.getCreateDate().getTime()) {
                    if(reportUser.getIsOvertime() == 0) {
                        return false;
                    }else {
                        workSummary.setStatus(2);
                    }
                }
            }else { //次日
                Date d  = sdf.parse(year + "-" + month + "-" + (day + 1) + " " + time[1] + ":" + time[2]);
                if(d.getTime() < workSummary.getCreateDate().getTime()) {
                    if(reportUser.getIsOvertime() == 0) {
                        return false;
                    }else {
                        workSummary.setStatus(2);
                    }
                }
            }
        }

        if(workSummary.getType() == 2) { //周
            calendar.setTime(workSummary.getCreateDate());
            // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
            calendar.setFirstDayOfWeek(Calendar.MONDAY);
            // 判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
            int dayWeek = calendar.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
            if (1 == dayWeek) {
                calendar.add(Calendar.DAY_OF_MONTH, -1);
            }
            // 获得当前日期是一个星期的第几天
            int week = calendar.get(Calendar.DAY_OF_WEEK);
            if(time[0].equals("1")) { //当周
                Date d  = sdf.parse(year + "-" + month + "-" + (day + (Integer.parseInt(time[1]) - week)) + " " + time[2] + ":" + time[3]);
                if(d.getTime() < workSummary.getCreateDate().getTime()) {
                    if(reportUser.getIsOvertime() == 0) {
                        return false;
                    }else {
                        workSummary.setStatus(2);
                    }
                }
            }else { //次周
                Date d  = sdf.parse(year + "-" + month + "-" + (day + (Integer.parseInt(time[1]) - week) + 7) + " " + time[2] + ":" + time[3]);
                if(d.getTime() < workSummary.getCreateDate().getTime()) {
                    if(reportUser.getIsOvertime() == 0) {
                        return false;
                    }else {
                        workSummary.setStatus(2);
                    }
                }
            }
        }

        if(workSummary.getType() == 3) { //月
            if(time[0].equals("1")) { //当月
                Date d  = sdf.parse(year + "-" + month + "-" + time[1] + " " + time[2] + ":" + time[3]);
                if(d.getTime() < workSummary.getCreateDate().getTime()) {
                    if(reportUser.getIsOvertime() == 0) {
                        return false;
                    }else {
                        workSummary.setStatus(2);
                    }
                }
            }else { //次月
                Date d  = sdf.parse(year + "-" + (month + 1) + "-" + time[1] + " " + time[2] + ":" + time[3]);
                if(d.getTime() < workSummary.getCreateDate().getTime()) {
                    if(reportUser.getIsOvertime() == 0) {
                        return false;
                    }else {
                        workSummary.setStatus(2);
                    }
                }
            }
        }
        return true;
    }
}
